package com.abigdreamer.im.client.module.network.socket;

import java.net.InetSocketAddress;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import com.abigdreamer.im.client.module.network.handler.ClientChatHandler;
import com.abigdreamer.im.client.util.EIMLogger;

/**
 * 客户的聊天消息发送socket 单例
 */
public class ClientChatSocket extends EIMClientSocket {

	private static ClientChatSocket instance;

	public static ClientChatSocket getInstance() {
		if (instance == null) {
			instance = new ClientChatSocket();
		}
		return instance;
	}

	private ClientChatSocket() {
	}

	public boolean closedSocket() {
		this.getConnector().dispose();
		this.setStart(false);
		EIMLogger.INFO("客户关闭了与服务器的连接");
		return true;
	}

	public void initSocket() {
		this.setHandlerAdapter(new ClientChatHandler());
		this.setConnector(new NioSocketConnector());
		EIMLogger.INFO("客户初始化了与服务器的连接");
	}

	/**
	 * 
	 */
	public boolean startSocket() {
		this.initSocket();
		try {
			EIMLogger.INFO("是否开启连接：" + this.isStart());
			if (this.isStart() == false) {
				/** 创建接收数据的过滤器 */
				EIMLogger.INFO("创建接收数据的过滤器");
				DefaultIoFilterChainBuilder chain = this.getConnector().getFilterChain();
				ObjectSerializationCodecFactory objscf = new ObjectSerializationCodecFactory();
				ProtocolCodecFilter protocolCodecFilter = new ProtocolCodecFilter(objscf);
				chain.addLast("myTextChain", protocolCodecFilter);
				this.getConnector().setHandler(this.getHandlerAdapter());
				EIMLogger.INFO("设置连接超时的时间 为：一分钟 这个超时不可以过小:" + EIMClientSocket.timeOutMillis);
				/** 设置连接超时的时间 为：一分钟 这个超时不可以过小 */
				this.getConnector().setConnectTimeoutMillis(EIMClientSocket.timeOutMillis);
				EIMLogger.INFO("ip/port:" + this.getServer_IP_Port() + "/" + this.getServer_Socket_Port());
				InetSocketAddress textInetSocketAddress = new InetSocketAddress(this.getServer_IP_Port(), this.getServer_Socket_Port());
				/** 建立连接 */
				this.connectFuture = this.getConnector().connect(textInetSocketAddress);
				EIMLogger.INFO("已经建立用户的连接");
				this.setStart(true);
				EIMLogger.INFO("客户开启了与服务器的连接");
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

	}

}
